<template>
  <el-card class="auth-card">
    <el-tabs v-model="activeTab" stretch>
      <el-tab-pane label="登录" name="login">
        <el-form
          :model="loginForm"
          :rules="rulesLogin"
          ref="loginFormRef"
          @submit.prevent="handleLogin"
          label-width="80px"
        >
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="loginForm.email" autocomplete="email" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              autocomplete="current-password"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       native-type="submit"
                       style="width: 100%"
            >登录</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="warning"
                       style="width: 100%"
                       @click="showAdminDialog = true"
            >管理员登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="注册" name="register" :rules="rulesRegister">
        <el-form
          :model="registerForm"
          :rules="rulesRegister"
          ref="registerFormRef"
          @submit.prevent="handleRegister"
          label-width="80px"
        >
          <el-form-item label="用户名" required prop="name">
            <el-input v-model="registerForm.name" autocomplete="name" />
          </el-form-item>
          <el-form-item label="邮箱" required prop="email">
            <el-input v-model="registerForm.email" autocomplete="email" />
          </el-form-item>
          <el-form-item label="密码" required prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              autocomplete="new-password"
            />
          </el-form-item>
          <el-form-item label="确认密码" required prop="password_confirmation">
            <el-input
              v-model="registerForm.password_confirmation"
              type="password"
              autocomplete="new-password"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       native-type="submit"
                       style="width: 100%"
            >注册</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-alert
      v-if="message"
      :title="message"
      type="error"
      show-icon
      style="margin-top: 16px"
    />

    <el-dialog
      v-model="showAdminDialog"
      title="管理员登录"
      width="350px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="adminForm"
        :rules="rulesLogin"
        ref="adminFormRef"
        @submit.prevent="handleAdminLogin"
        label-width="80px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" autocomplete="email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="adminForm.password"
            type="password"
            autocomplete="current-password"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     native-type="submit"
                     style="width: 100%"
          >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import { FormRules } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();

const activeTab = ref('login');
const loginForm = ref({ email: '', password: '' });
const registerForm = ref({
  name: '',
  email: '',
  password: '',
  password_confirmation: ''
});
const message = ref('');
const loginFormRef = ref();
const registerFormRef = ref();
const showAdminDialog = ref(false);
const adminForm = ref({ email: '', password: '' });
const adminFormRef = ref();
// 管理员登录
const handleAdminLogin = async() => {
  await adminFormRef.value?.validate(async(valid: boolean) => {
    if (!valid) return;
    try {
      await userStore.adminLogin(adminForm.value);
      ElMessage.success('管理员登录成功！');
      showAdminDialog.value = false;
      setTimeout(() => {
        router.replace('/system/contentManagement');
      }, 500);
    } catch (error) {
      ElMessage.error('管理员账号或密码错误！');
      console.error(error);
    }
  });
};
const rulesLogin: FormRules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度不得少于8位', trigger: 'blur' }
  ]
});

const rulesRegister: FormRules = reactive({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 2,
      max: 20,
      message: '长度在2 到 20 个字符',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback();
          return;
        }
        if (value.length < 8) {
          callback(new Error('密码长度不得少于8位'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  password_confirmation: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { min: 8, message: '密码长度不得少于8位', trigger: 'blur' }
  ]
});

// 登录
const handleLogin = async() => {
  message.value = '';
  await loginFormRef.value?.validate(async(valid: boolean) => {
    if (!valid) return;
    try {
      await userStore.login(loginForm.value);
      ElMessage.success('登录成功！');
      setTimeout(() => {
        router.replace('/home');
      }, 500);
    } catch (error) {
      message.value = '账号或密码错误！';
      console.error(error);
    }
  });
};

// 注册
const handleRegister = async() => {
  message.value = '';
  await registerFormRef.value?.validate(async(valid: boolean) => {
    if (!valid) return;
    if (registerForm.value.password !== registerForm.value.password_confirmation) {
      message.value = '两次输入的密码不一致！';
      return;
    }
    try {
      await userStore.register(registerForm.value);
      ElMessage.success('注册成功！');
      router.replace('/home');
    } catch (error) {
      message.value = '注册失败！';
      console.error(error);
    }
  });
};
</script>

<style scoped lang="scss">
.auth-card {
  max-width: 400px;
  margin: 30vh auto;
  padding: 24px 16px;
}
</style>
